package com.xyongfeng.foodManagement.shiro;

import com.xyongfeng.foodManagement.domain.AdminInfo;
import com.xyongfeng.foodManagement.service.AdminInfoService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.List;

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    AdminInfoService adminInfoService;


    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取前端传来的token
        UsernamePasswordToken accessToken = (UsernamePasswordToken) token;
        // 获取用户信息
        AdminInfo user = adminInfoService.findByUsername(accessToken.getUsername());
        if (user == null) {
            throw new UnknownAccountException("用户不存在!");
        }

        //此方法需要返回一个AuthenticationInfo类型的数据
        // 因此返回一个它的实现类SimpleAuthenticationInfo,将user以及获取到的token传入它可以实现自动认证
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, accessToken.getUsername(), "");
        return simpleAuthenticationInfo;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //从认证那里获取到用户对象admin
        AdminInfo adminInfo = (AdminInfo) principals.getPrimaryPrincipal();

        //此方法需要一个AuthorizationInfo类型的返回值，因此返回一个它的实现类SimpleAuthorizationInfo 
        //通过SimpleAuthorizationInfo里的addStringPermission()设置用户的权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(adminInfo.getPermissions());

        return simpleAuthorizationInfo;
    }
}